import 'package:example/pages/todo/todo_item.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:getx_scaffold_ohos/getx_scaffold_ohos.dart';

import '../../models/todo_entity.dart';
import 'todo_controller.dart';

class TodoPage extends StatelessWidget {
  TodoPage({super.key});

  final TodoController controller = Get.put(TodoController());

  void _showAddTodoDialog() => _showTodoDialog(isEditing: false);

  void _showEditTodoDialog(TodoEntity todo) =>
      _showTodoDialog(todo: todo, isEditing: true);

  void _showTodoDialog({TodoEntity? todo, required bool isEditing}) {
    final titleController = TextEditingController(text: todo?.title ?? '');
    final descController = TextEditingController(text: todo?.content ?? '');
    DateTime selectedDate = DateTime.now();
    if(todo != null){
      selectedDate = DateTime.fromMillisecondsSinceEpoch(todo.date!);
    }

    Get.dialog(AlertDialog(
      title: Text(isEditing ? '编辑待办' : '添加待办'),
      content: SingleChildScrollView(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            TextField(
              controller: titleController,
              decoration: InputDecoration(
                labelText: '标题',
                border: OutlineInputBorder(),
              ),
              autofocus: true,
            ),
            SizedBox(height: 16),
            TextField(
              controller: descController,
              decoration: InputDecoration(
                labelText: '内容 (可选)',
                border: OutlineInputBorder(),
              ),
              maxLines: 3,
            ),
            SizedBox(height: 16),
            Row(
              children: [
                Icon(Icons.calendar_today, size: 20),
                SizedBox(width: 8),
                Text(
                  DateFormat('MMM dd, yyyy').format(selectedDate),
                  style: TextStyle(fontSize: 16),
                ),
                Spacer(),
                TextButton(
                  child: Text('选择日期'),
                  onPressed: () async {
                    final pickedDate = await showDatePicker(
                      context: Get.context!,
                      initialDate: selectedDate,
                      firstDate: DateTime(2000),
                      lastDate: DateTime(2100),
                    );
                    if (pickedDate != null) {
                      selectedDate = pickedDate;
                      (Get.context! as Element).markNeedsBuild();
                    }
                  },
                ),
              ],
            ),
          ],
        ),
      ),
      actions: [
        TextButton(
          onPressed: () => Get.back(),
          child: Text('取消'),
        ),
        ElevatedButton(
          onPressed: () async {
            if (titleController.text.trim().isEmpty) {
              Get.showSnackbar(GetSnackBar(message: '请输入标题',));
              return;
            }

            final newTodo = todo ?? TodoEntity();
            newTodo
            ..title = titleController.text.trim()
            ..content = descController.text.trim()
            ..date = selectedDate.millisecondsSinceEpoch;

            if (isEditing) {
              await controller.updateTodo(newTodo);
            } else {
              await controller.addTodo(newTodo);
            }
            Get.back();
          },
          child: Text(isEditing ? 'Save' : 'Add'),
        ),
      ],
    ));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        elevation: 0.5,
        title: const Text('Todo'),
        actions: [IconButton(onPressed: () => _showAddTodoDialog(), icon: const Icon(Icons.add))],
      ),
      body: GetBuilder(
        tag: 'todo',
        init: controller,
        builder: (controller) {
          return controller.list.isEmpty
              ? const Center(
                  child: Text('暂无待办\n点击 + 添加'),
                )
              : ListView.separated(
                  padding: const EdgeInsets.all(16),
                  separatorBuilder: (context, index) => const SizedBox(
                    height: 12,
                  ),
                  itemCount: controller.list.length,
                  itemBuilder: (context, index) {
                    final todo = controller.list[index];
                    return TodoItem(
                      todo: todo,
                      onEdit: (TodoEntity todo) => _showEditTodoDialog(todo),
                    );
                  },
                );
        },
      ),
    );
  }
}
